package com.akl.ssmspringboot.controller;

import com.akl.ssmspringboot.entity.Login;
import com.akl.ssmspringboot.service.LoginService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * @ClassName:
 * @Author: Guoxy
 * @Date: Created in 16:54 2018/11/30
 * @Version:1.0
 */
@Controller
public class LoginController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private LoginService loginService;

    @RequestMapping("/login")
    public ModelAndView login(Login login, HttpServletRequest request){
        ModelAndView mv = new ModelAndView();
        String loginName = login.getLoginName();
        String password = login.getPassword();
        if (null == loginName || null == password) {
            mv.setViewName("/login");
        }
        if(loginName != null && password != null){
            Boolean bool = loginService.checkLogin(loginName, password);
            if(bool){
                mv.setViewName("redirect:/dataTables/table");
                // 校验通过时，在session里放入一个标识
                // 后续通过session里是否存在该标识来判断用户是否登录
                request.getSession().setAttribute("loginName", loginName);
                logger.info("登录成功");
            }
        }
        return mv;
    }

    /**
     * 注销登录
     * @param request
     * @return
     */
    @RequestMapping("/loginOut")
    public String loginOut(HttpServletRequest request) {
        request.getSession().invalidate();
        logger.info("注销登录");
        return "redirect:/login";
    }

}
